package com.irdstudio.tdp.executor.rest.api.rest;

import com.irdstudio.tdp.executor.rest.api.rest.vo.ResponseVO;
import com.irdstudio.tdp.executor.rest.init.ExecutorResourceLoader;
import com.irdstudio.tdp.executor.rest.job.BatchStarter;
import com.irdstudio.tdp.executor.core.batch.BatchRunEngine;
import com.irdstudio.sdk.beans.core.util.FileUtil;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.Objects;

@RestController
@RequestMapping("/executor")
public class BatchController implements InitializingBean {

    private static final Logger logger = LoggerFactory.getLogger(BatchStarter.class);

    @Value("${agent.batch.log.path}")
    private String logPath;

    @RequestMapping(value = "/batch/start", method = RequestMethod.GET)
    public ResponseVO startBatch(@RequestParam("batchSerialNo") String batchSerialNo, @RequestParam("batchId") String batchId, @RequestParam("batchAction") String batchAction) {
        logger.info("日终服务执行调用开始");
        ResponseVO vo = new ResponseVO();
        try {
            logger.info("日终服务执行开始, 批次ID：" + batchId + ", 批次动作：" + batchAction);
            if (StringUtils.isNotBlank(batchSerialNo)) {
                BatchRunEngine batchEngine = new BatchRunEngine(batchSerialNo, batchAction, batchId);
                batchEngine.start();
            } else {
                BatchRunEngine batchEngine = new BatchRunEngine(batchAction, batchId);
                batchEngine.start();
            }

            vo.setFlag("success");
            vo.setMsg("成功执行批次");
        } catch (Exception e) {
            logger.error("日终服务执行出错！", e);
        }
        logger.info("日终服务执行调用结束");
        return vo;
    }

    @RequestMapping(value = "/batch/log", method = RequestMethod.GET)
    public ResponseVO getBatchRunLogs(@RequestParam("batchId") String batchId) {
        logger.info("获取批次日志信息开始，批次号:" + batchId);
        ResponseVO responseVO = new ResponseVO();
        try {
            File file = new File(logPath);
            if (file.exists() && Objects.nonNull(file.listFiles())) {
                File[] files = file.listFiles();
                for (File f : files) {
                    if (f.isFile() && f.getName().contains(batchId)) {
                        String output = FileUtil.readFileByLines(f.getAbsolutePath());
                        responseVO.setFlag(ResponseVO.SUCCESS);
                        responseVO.setMsg(output);
                    }
                }
            } else {
                throw new Exception("路径:" + logPath + "，不存在文件");
            }
        } catch (Exception e) {
            logger.error("获取批次日志信息出错，批次号:" + batchId);
            e.printStackTrace();
            responseVO.setFlag(ResponseVO.FAIL);
            responseVO.setMsg(e.getMessage());
        }
        return responseVO;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        // 加载全局参数
        ExecutorResourceLoader.me().start();
    }
}
